package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.base.ResponseResult;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceimpl implements WechatService {
    private static final String USER_LOGIN_KEY = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    private static final String PHONE_Url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String Token_Url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    @Value("${zzyl.framework.wechat.appId}")
    private String appId;
    @Value("${zzyl.framework.wechat.appSecret}")
    private String secret;

    @Override
    public String getOpenId(String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("js_code",code);

        String s = HttpUtil.get(USER_LOGIN_KEY, map);
        JSONObject entries = JSONUtil.parseObj(s);

        String openid = (String) entries.get("openid");
        return openid;
    }

    @Override
    public String getPhone(String phoneCode) {
        //获取access_token
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        String res = HttpUtil.get(Token_Url, map);
        JSONObject entries = JSONUtil.parseObj(res);
        String accessToken = (String) entries.get("access_token");

        //获取电话号码
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("code", phoneCode);
        String result = HttpUtil.post(PHONE_Url + accessToken, JSONUtil.toJsonStr(map1));
        JSONObject entries2 = JSONUtil.parseObj(result);

        String phoneInfo = entries2.getStr("phone_info");
        JSONObject entries1 = JSONUtil.parseObj(phoneInfo);
        return entries1.getStr("phoneNumber");
    }

    //公共
    /*private Map<String, Object> getMap() {

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", appId);
        requestUrlParam.put("secret", secret);
        return requestUrlParam;
    }*/


}
